package com.chen.authority.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.authority.common.annotation.Log;
import com.chen.authority.common.enums.BusinessType;
import com.chen.authority.common.response.PageResponse;
import com.chen.authority.common.response.Response;
import com.chen.authority.common.response.SingleResponse;
import com.chen.authority.common.util.FileUtil;
import com.chen.authority.common.util.MinioUtil;
import com.chen.authority.common.util.WrapperUtil;
import com.chen.authority.model.qo.FileQo;
import com.chen.authority.common.model.PageQo;
import com.chen.authority.model.po.FilePo;
import com.chen.authority.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * 文件管理
 *
 * @author chengy
 * @date 2022/11/19
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
@Api(tags = "文件管理 FileController")
public class FileController {

    private final FileService fileService;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    @SaCheckPermission("system:file:upload")
    @Log(module = "系统管理-文件管理", businessType = BusinessType.INSERT)
    public Response upload(@ApiParam(required = true) MultipartFile file, String remark) {
        if (FileUtil.isEmpty(file)) {
            return Response.fail("上传文件为空");
        }
        String url = MinioUtil.uploadFile(file);
        boolean result = fileService.saveUploadFileInfo(file.getOriginalFilename(), file.getSize(), url, remark);
        return result ? SingleResponse.success(url) : Response.fail();
    }

    @DeleteMapping
    @ApiOperation("删除文件")
    @SaCheckPermission("system:file:delete")
    @Log(module = "系统管理-文件管理", businessType = BusinessType.DELETE)
    public Response delete(String[] filenames) {
        MinioUtil.deleteFiles(Arrays.asList(filenames));
        boolean result = fileService.remove((Wrappers.<FilePo>lambdaQuery().in(FilePo::getFilename, filenames)));
        return result ? Response.success() : Response.fail();
    }

    @PostMapping
    @ApiOperation("下载文件")
    @SaCheckPermission("system:file:download")
    @Log(module = "系统管理-文件管理", businessType = BusinessType.DOWNLOAD)
    public void download(HttpServletResponse response, String filename) {
        MinioUtil.downloadFile(response, filename);
    }

    @GetMapping("/list")
    @ApiOperation("查询文件列表")
    @SaCheckPermission("system:file:list")
    public PageResponse<FilePo> list(PageQo pageQo, FileQo fileQo) {
        return PageResponse.success(fileService.page(pageQo.build(), WrapperUtil.buildQueryWrapper(fileQo)));
    }

}